package com.power.using.sharlockchat.fragment;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.power.using.sharlockchat.R;
import com.power.using.sharlockchat.base.BaseMainFragment;
import com.power.using.sharlockchat.http.HttpApi;
import com.power.using.sharlockchat.http.Request;
import com.power.using.sharlockchat.utils.HttpUtils;
import com.power.using.sharlockchat.utils.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;

/**
 * Created by 聪明一只哈 on 2018/5/25.
 * Time: 2018/5/25  10:35
 */

public class FileOutFrament extends BaseMainFragment {


    private TextView toolTitle;
    private TextView tv_start_time;
    private TextView tv_end_time;
    private Button btTest;
    private ImageButton imageFileButton;
    private long starTimeLong;
    private long endTimeLong;
    private ProgressDialog dialog;
    private String saveFilePath;

    public static FileOutFrament newInstance() {

        Bundle args = new Bundle();

        FileOutFrament fragment = new FileOutFrament();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_three, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        toolTitle = (TextView) view.findViewById(R.id.toolbar_title);
        btTest = (Button) view.findViewById(R.id.bt_test);
        imageFileButton = (ImageButton) view.findViewById(R.id.imageDileButton);
        tv_start_time = (TextView) view.findViewById(R.id.tv_start_time);
        tv_end_time = (TextView) view.findViewById(R.id.tv_end_time);
        toolTitle.setText("测试数据");
    }

    //懒加载

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initMZBanner();
//        initRVData();
//        initListener();
    }

    private void initMZBanner() {
        btTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String startTime = tv_start_time.getText().toString().trim();
                String endTime = tv_end_time.getText().toString().trim();
                if (TextUtils.isEmpty(startTime)) {
                    ToastUtils.showLongToast(_mActivity, "请选择起始时间");
                    return;
                }
                if (TextUtils.isEmpty(endTime)) {
                    ToastUtils.showLongToast(_mActivity, "请选择结束时间");
                    return;
                }

                try {
                    starTimeLong = new SimpleDateFormat("yyyy-MM-dd").parse(startTime).getTime();
                    endTimeLong = new SimpleDateFormat("yyyy-MM-dd").parse(endTime).getTime();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (endTimeLong < starTimeLong) {
                    ToastUtils.showLongToast(_mActivity, "结束时间不能在起始时间之前");
                    return;
                }


                if (!startTime.equals(endTime)) {
                    ToastUtils.showLongToast(_mActivity, "导出文件");
                    getDate();
                }


            }
        });


        tv_start_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onYearMonthDayPicker("first");
            }
        });
        tv_end_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onYearMonthDayPicker("end");
            }
        });

        imageFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(saveFilePath) && saveFilePath != null) {
                    Intent intent = getWordFileIntent(saveFilePath);
                    startActivity(intent);

//                    if(isInstall(_mActivity, "cn.wps.moffice_eng")){
//
//                    }else{
//                        ToastUtils.showLongToast(_mActivity,"没有安装WPS");
//                    }

//                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                    intent.setDataAndType(Uri.fromFile(new File(saveFilePath)), "*/*");
//                    intent.addCategory(Intent.CATEGORY_OPENABLE);
//                    startActivity(intent);

                    //打开文件管理器
//                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                    intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
//                    intent.addCategory(Intent.CATEGORY_OPENABLE);
//                    startActivity(intent);
                }

            }
        });
    }

    public void onYearMonthDayPicker(String tv_flag) {
        final DatePicker picker = new DatePicker(getActivity());
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(getActivity(), 10));
        picker.setRangeEnd(2022, 1, 1);
        picker.setRangeStart(2019, 1, 1);
        picker.setSelectedItem(2019, 1, 1);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {

                if ("first".equals(tv_flag)) {
                    tv_start_time.setText("" + year + "-" + month + "-" + day);
                } else if ("end".equals(tv_flag)) {
                    tv_end_time.setText("" + year + "-" + month + "-" + day);
                }
                Toast.makeText(getActivity(), year + "-" + month + "-" + day, Toast.LENGTH_SHORT).show();
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    private void getDate() {

        dialog = new ProgressDialog(_mActivity);
        dialog.setTitle("正在下载");
        dialog.setMessage("正在下载中....");
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


        HttpUtils.requestDownloadFile(_mActivity, HttpApi.GET_FILE, "", "数据表格.xlsx", new Request() {

            @Override
            public void onBefore() {
                super.onBefore();

            }

            @Override
            public void onProgress(float progress) {
                dialog.show();
                int pro = (int) (100 * progress);
                dialog.setProgress(pro);
                Log.i("testDates", pro + "~~" + progress);
                if ((int) (100 * progress) == 100) {
                    tv_start_time.setHint("点击选择");
                    tv_end_time.setHint("点击选择");

                    dialog.dismiss();
                }
            }

            @Override
            public void successFile(File file) {
                super.successFile(file);

                saveFilePath = file.getAbsolutePath();
                Log.i("testDate", "success: " + file.getAbsolutePath());
                imageFileButton.setVisibility(View.VISIBLE);

            }

            @Override
            public void error(String error) {
                super.error(error);
                Log.i("testDate", "error: " + error);
                dialog.dismiss();
                ToastUtils.showLongToast(_mActivity,"网络连接失败");
            }
        });
    }

    /**
     * 打开下载文件
     *
     * @param Path
     * @return
     */
    private Intent getWordFileIntent(String Path) {
        File file = new File(Path);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(file);
        String type = getMIMEType(file);
        if (type.contains("pdf") || type.contains("vnd.ms-powerpoint") || type.contains("vnd.ms-word") || type.contains("vnd.ms-excel") || type.contains("text/plain") || type.contains("text/html")) {
            if (isInstall(_mActivity, "cn.wps.moffice_eng")) {

                intent.setClassName("cn.wps.moffice_eng",
                        "cn.wps.moffice.documentmanager.PreStartActivity2");
                intent.setData(uri);
            } else {
                ToastUtils.showLongToast(_mActivity, "请安装办公软件进行查看");
//                intent.addCategory("android.intent.category.DEFAULT");
//                intent.setDataAndType(uri, type);
            }
        } else {
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(uri, type);
        }
        return intent;
    }

    /**
     * 判断文件类型
     *
     * @param f
     * @return
     */
    private static String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/vnd.ms-word";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else if (end.equals("txt")) {
            type = "text/plain";
        } else if (end.equals("html") || end.equals("htm")) {
            type = "text/html";
        } else {
            //如果无法直接打开，就跳出软件列表给用户选择
            type = "*/*";
        }
        return type;
    }

    /**
     * 判断是否安装WPS
     *
     * @param context
     * @param packageName
     * @return
     */
    private boolean isInstall(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }


}
